<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { addAddressAPI, delAddressAPI, getAddressAPI, updateAddressAPI } from '@/apis/address'
import { regionData } from "element-china-area-data";

// 模拟地区数据
const regionOptions = ref([
  {
    value: '210000',
    label: '辽宁省',
    children: [
      {
        value: '210200',
        label: '大连市',
        children: [
          { value: '210202', label: '中山区' },
          { value: '210203', label: '西岗区' },
          { value: '210204', label: '沙河口区' }
        ]
      }
    ]
  }
  // 可以添加更多省份数据
])

// 地址列表数据
const addressList = ref([
  {
    id: '1543553507431288834',
    receiver: '老李',
    contact: '13900002020',
    provinceCode: '210000',
    cityCode: '210200',
    countyCode: '210202',
    address: 'xxx街xxx路',
    isDefault: 1,
    fullLocation: '辽宁省大连市中山区',
    postalCode: '111006',
    addressTags: '家里'
  },
  {
    id: '1543553507431288835', // 收货地址id
    receiver: '王女士', // 收货人-姓名
    contact: '13800003030', // 收货人-联系方式
    provinceCode: '110000',// 收货人-省份编码
    cityCode: '110100', // 收货人-城市编码
    countyCode: '110101', // 收货人-地区编码
    address: 'yyy街yyy路', // 收货人-详细地址
    isDefault: 0, // 0是 默认地址, 1不是默认地址
    fullLocation: '北京市东城区', // 收货人-完整地址
    postalCode: '100010', // 收货人-邮政编码
    addressTags: '公司' // 收货人-地址标签 如果有多个, 是英文逗号分割的
  }
])
const getAddrsssList = async () => {
  const res = await getAddressAPI()
  addressList.value = res.result
}

onMounted(() => {
  getAddrsssList(),
  regionOptions.value = regionData
})

// 对话框状态
const dialogVisible = ref(false)
const isEditMode = ref(false)
const addressForm = ref(null)

// 当前编辑的地址
const currentAddress = reactive({
  id: '',
  receiver: '',
  contact: '',
  selectedRegion: [],
  address: '',
  isDefault: 1,
  fullLocation: '',
  postalCode: '',
  addressTags: '',
  addressTagsArr: []
})

// 表单验证规则
const addressRules = reactive({
  receiver: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  contact: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  selectedRegion: [
    { required: true, message: '请选择所在地区', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  postalCode: [
    { pattern: /^[1-9]\d{5}$/, message: '请输入正确的邮政编码', trigger: 'blur' }
  ]
})

// 添加新地址
const handleAddAddress = () => {
  isEditMode.value = false
  resetCurrentAddress()
  dialogVisible.value = true
}

// 编辑地址
const handleEditAddress = (address) => {
  isEditMode.value = true
  Object.assign(currentAddress, {
    id: address.id,
    receiver: address.receiver,
    contact: address.contact,
    selectedRegion: [address.provinceCode, address.cityCode, address.countyCode],
    address: address.address,
    isDefault: address.isDefault,
    postalCode: address.postalCode,
    addressTags: address.addressTags,
    addressTagsArr: address.addressTags.split(',')
  })
  dialogVisible.value = true
}

// 重置当前地址表单
const resetCurrentAddress = () => {
  Object.assign(currentAddress, {
    id: '',
    receiver: '',
    contact: '',
    selectedRegion: [],
    address: '',
    isDefault: 1,
    postalCode: '',
    addressTags: '',
    addressTagsArr: []
  })
}

// 提交地址表单
const submitAddress = async () => {
  try {
    await addressForm.value.validate()

    // 生成完整地区名称
    const regionNames = []
    const province = regionOptions.value.find(p => p.value === currentAddress.selectedRegion[0])
    if (province) {
      regionNames.push(province.label)
      const city = province.children.find(c => c.value === currentAddress.selectedRegion[1])
      if (city) {
        regionNames.push(city.label)
        const county = city.children.find(a => a.value === currentAddress.selectedRegion[2])
        if (county) {
          regionNames.push(county.label)
        }
      }
    }
    const fullLocation = regionNames.join(' ')

    const addressData = {
      // id: currentAddress.id || Date.now().toString(),
      receiver: currentAddress.receiver,
      contact: currentAddress.contact,
      provinceCode: currentAddress.selectedRegion[0],
      cityCode: currentAddress.selectedRegion[1],
      countyCode: currentAddress.selectedRegion[2],
      address: currentAddress.address,
      isDefault: currentAddress.isDefault,
      fullLocation,
      postalCode: currentAddress.postalCode,
      addressTags: currentAddress.addressTags
    }

    addressData.addressTags = currentAddress.addressTagsArr.join(',')

    if (isEditMode.value) {
      // 如果是编辑，把id也传递过去
      addressData.id = currentAddress.id
      // 调用接口更新地址
      await updateAddressAPI(addressData)
      // 更新成功后刷新地址列表
      getAddrsssList()
      // 更新地址
      // const index = addressList.value.findIndex(item => item.id === addressData.id)
      // if (index !== -1) {
      //   addressList.value.splice(index, 1, addressData)
      // }
    } else {
      // 添加新地址
      // addressList.value.unshift(addressData)
      // console.log(addressList.value);
      // 调用接口添加地址
      await addAddressAPI(addressData)
      // 添加成功后刷新地址列表
      getAddrsssList()
      // addressList.value = res.result
    }

    // 如果设置为默认地址，取消其他默认地址
    if (addressData.isDefault === 0) {
      addressList.value.forEach(item => {
        if (item.id !== addressData.id) {
          item.isDefault = 1
        }
      })
    }

    dialogVisible.value = false
    ElMessage.success(isEditMode.value ? '地址修改成功' : '地址添加成功')
  } catch (error) {
    console.log('表单验证失败', error)
  }
}

// 删除地址
const handleDeleteAddress = (id) => {
  ElMessageBox.confirm('确定要删除该地址吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const index = addressList.value.findIndex(item => item.id === id)
    if (index !== -1) {
      // 不能删除默认地址
      if (addressList.value[index].isDefault === 0) {
        ElMessage.warning('不能删除默认地址，请先设置其他地址为默认')
        return
      }
      // addressList.value.splice(index, 1)
      await delAddressAPI(id)
      // 删除成功后刷新地址列表
      await getAddrsssList()
      ElMessage.success('地址删除成功')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 设为默认地址
const handleSetDefault = async (id) => {
  await updateAddressAPI({
    id,
    isDefault: 0
  })
  await getAddrsssList()
  ElMessage.success('默认地址设置成功')
  // addressList.value.forEach(item => {
  //   item.isDefault = item.id === id ? 0 : 1
  // })
  // ElMessage.success('默认地址设置成功')
}

</script>

<template>
  <div class="address-management">
    <el-card class="address-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>地址管理</span>
          <el-button type="primary" size="small" @click="handleAddAddress">
            <el-icon><Plus /></el-icon>添加新地址
          </el-button>
        </div>
      </template>

      <!-- 地址列表 -->
      <div class="address-list">
        <div
          v-for="address in addressList"
          :key="address.id"
          class="address-item"
          :class="{ 'default-address': address.isDefault === 0 }"
        >
          <div class="address-info">
            <div class="address-header">
              <span class="receiver">{{ address.receiver }}</span>
              <span class="contact">{{ address.contact }}</span>
              <el-tag v-if="address.isDefault === 0" type="success" size="small">默认</el-tag>
              <el-tag v-if="address.addressTags" type="info" size="small">
                {{ address.addressTags }}
              </el-tag>
            </div>
            <div class="address-detail">
              {{ address.fullLocation }} {{ address.address }}
            </div>
            <div class="address-extra">
              邮政编码: {{ address.postalCode }}
            </div>
          </div>
          <div class="address-actions">
            <el-button
              type="primary"
              link
              @click="handleEditAddress(address)"
            >
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDeleteAddress(address.id)"
            >
              <el-icon><Delete /></el-icon>删除
            </el-button>
            <el-button
              v-if="address.isDefault !== 0"
              link
              @click="handleSetDefault(address.id)"
            >
              设为默认
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 添加/编辑地址对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑地址' : '添加新地址'"
      width="50%"
    >
      <el-form
        ref="addressForm"
        :model="currentAddress"
        label-width="100px"
        :rules="addressRules"
      >
        <el-form-item label="收货人" prop="receiver">
          <el-input v-model="currentAddress.receiver" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contact">
          <el-input v-model="currentAddress.contact" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="所在地区" prop="selectedRegion">
          <!-- <xtx-cascader :selectValue="valueModel" :size="'medium'" :parameters="'code'" :options="regionData" :placeholder="'请选择城市'" :style="'width: 100%'" @change="customChangeHandler" >
          </xtx-cascader> -->
          <el-cascader
            v-model="currentAddress.selectedRegion"
            :options="regionOptions"
            placeholder="请选择省市区"
            :props="{ value: 'value', label: 'label' }"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="currentAddress.address"
            type="textarea"
            :rows="2"
            placeholder="请输入详细地址"
          />
        </el-form-item>
        <el-form-item label="邮政编码" prop="postalCode">
          <el-input v-model="currentAddress.postalCode" placeholder="请输入邮政编码" />
        </el-form-item>
        <el-form-item label="地址标签" prop="addressTags">
          <el-select
            v-model="currentAddress.addressTagsArr"
            multiple
            placeholder="请选择地址标签"
            clearable
          >
            <el-option label="家里" value="家里" />
            <el-option label="公司" value="公司" />
            <el-option label="学校" value="学校" />
          </el-select>
        </el-form-item>
        <el-form-item label="默认地址">
          <el-switch
            v-model="currentAddress.isDefault"
            :active-value="0"
            :inactive-value="1"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddress">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.address-management {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.address-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.address-item {
  display: flex;
  justify-content: space-between;
  padding: 16px;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  transition: all 0.3s;
}

.address-item:hover {
  border-color: var(--el-color-primary);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.default-address {
  border-color: var(--el-color-primary);
  background-color: rgba(64, 158, 255, 0.05);
}

.address-info {
  flex: 1;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  gap: 8px;
}

.address-header .receiver {
  font-weight: bold;
  font-size: 16px;
}

.address-header .contact {
  color: var(--el-text-color-secondary);
}

.address-detail {
  margin-bottom: 4px;
  color: var(--el-text-color-regular);
}

.address-extra {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.address-actions {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 8px;
}
</style>
